/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * Copyright (C) 2016-2020 the AndroidAnnotations project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JExpr;
import com.helger.jcodemodel.JFieldRef;
import com.helger.jcodemodel.JFieldVar;
import com.helger.jcodemodel.JMethod;
import com.helger.jcodemodel.JVar;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.annotations.DataBound;
import org.ohosannotations.annotations.EAbility;
import org.ohosannotations.helper.IdValidatorHelper;
import org.ohosannotations.holder.EAbilityHolder;
import org.ohosannotations.rclass.IRClass;

import java.util.List;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

/**
 * eability处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public class EAbilityHandler extends CoreBaseGeneratingAnnotationHandler<EAbilityHolder> {
    /**
     * eability处理程序
     *
     * @param environment 环境
     */
    public EAbilityHandler(OhosAnnotationsEnvironment environment) {
        super(EAbility.class, environment);
    }

    /**
     * 创建生成类持有人
     *
     * @param environment 环境
     * @param annotatedElement 带注释的元素
     * @return {@link EAbilityHolder}
     * @throws Exception 异常
     */
    @Override
    public EAbilityHolder createGeneratedClassHolder(OhosAnnotationsEnvironment environment,
        TypeElement annotatedElement) throws Exception {
        return new EAbilityHolder(environment, annotatedElement, getEnvironment().getOhosManifest());
    }

    /**
     * 验证
     *
     * @param element 元素
     * @param valid 有效的
     */
    @Override
    public void validate(Element element, ElementValidation valid) {
        super.validate(element, valid);
        validatorHelper.extendsAbility(element, valid);
        validatorHelper.resIdsExist(element, IRClass.Res.LAYOUT,
            IdValidatorHelper.FallbackStrategy.ALLOW_NO_RES_ID, valid);
        coreValidatorHelper.checkDataBoundAnnotation(element, valid);
    }

    /**
     * 过程
     *
     * @param element 元素
     * @param holder 持有人
     */
    @Override
    public void process(Element element, EAbilityHolder holder) {
        List<JFieldRef> fieldRefs = annotationHelper
            .extractAnnotationFieldRefs(element, IRClass.Res.LAYOUT, false);
        JFieldRef contentViewId = null;
        if (fieldRefs.size() == 1) {
            contentViewId = fieldRefs.get(0);
        }

        if (contentViewId == null) {
            return;
        }

        JBlock onCreateBody = holder.getOnStart().body();
        JMethod setContentView = holder.getSetContentViewLayout();

        if (element.getAnnotation(DataBound.class) != null) { // 暂时不支持此注解
            JFieldRef ohosContentResId = null;
            JVar contentView = onCreateBody.decl(getClasses().COMPONENT_CONTAINER,
                "contentView", JExpr.invoke("internalFindViewById").arg(ohosContentResId));
            JFieldVar bindingField = holder.getDataBindingField();
            onCreateBody.assign(bindingField, holder
                .getDataBindingInflationExpression(contentViewId, contentView, false));
            onCreateBody.invoke(setContentView).arg(bindingField.invoke("getRoot"))
                .arg(bindingField.invoke("getRoot").invoke("getLayoutParams"));
            holder.getOnDestroyBeforeSuperBlock().invoke(bindingField, "unbind");
        } else {
            JVar contentView = onCreateBody.decl(getClasses().COMPONENT_CONTAINER, "contentView",
                JExpr.cast(getClasses().COMPONENT_CONTAINER, getClasses()
                    .LAYOUT_SCATTER.staticInvoke("getInstance")
                    .arg(JExpr._this()).invoke("parse")
                    .arg(contentViewId)
                    .arg(JExpr._null()).arg(JExpr.FALSE)));
            onCreateBody.invoke(setContentView).arg(contentView);
        }
    }
}
